package com.common.util.utils;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @文件名称：DeviceUtils.java
 * @文件作者：ljb
 * @文件描述：设备信息
 * @版本： 1.0.0
 * @创建时间：2017-12-20 15:10
 * @修改历史：2017-12-20 15:10
 */

public class DeviceUtils {


    public static String buildSystemInfo(Context context) {
        StringBuilder sb = new StringBuilder();
        sb.append("\n");
        sb.append("#-------system info-------");
        sb.append("\n");
        sb.append("version-name:");
        sb.append(AppUtils.getVersionName());
        sb.append("\n");
        sb.append("version-code:");
        sb.append(AppUtils.getVersionCode());
        sb.append("\n");
        sb.append("system-version:");
        sb.append(getSystemVersion());
        sb.append("\n");
        sb.append("model:");
        sb.append(getModel());
        sb.append("\n");
        sb.append("density:");
        sb.append(ScreenUtils.getDensity(context));
        sb.append("\n");
        sb.append("imei:");
        sb.append(getIMEI(context));
        sb.append("\n");
        sb.append("screen-height:");
        sb.append(ScreenUtils.getScreenHeight(context));
        sb.append("\n");
        sb.append("screen-width:");
        sb.append(ScreenUtils.getScreenWidth(context));
        sb.append("\n");
        sb.append("unique-code:");
        sb.append(getUniqueCode(context));
        sb.append("\n");
        sb.append("mobile:");
        sb.append(getMobile(context));
        sb.append("\n");
        sb.append("imsi:");
        sb.append(getProvider(context));
        sb.append("\n");
        sb.append("isWifi:");
        sb.append(NetworkUtils.isWifi(context));

//        sb.append("\n");
//        sb.append("IpAddress:");
//        sb.append(NetworkUtils.getIpAddress(context));
//        sb.append("\n");
//        sb.append("getNetworkTypeName:");
//        sb.append(NetworkUtils.getNetworkTypeName(context));
//        sb.append("\n");
//        sb.append("isNetworkAvailable:");
//        sb.append(NetworkUtils.isNetworkAvailable(context));
//        sb.append("\n");
//        sb.append("isWifi:");
//        sb.append(NetworkUtils.isWifi(context));

        sb.append("\n");
        return sb.toString();
    }


    public static File getAppRootDir(Context context) {
        if (!sdAvilible()) {
            return null;
        }
        File file = Environment.getExternalStorageDirectory();
        File path = new File(file, AppUtils.getAppNametoPath(context));
        path.mkdirs();
        return path;
    }

    public static File getAppCachDir(Context context, String cachPath) {
        if (!sdAvilible()) {
            return null;
        }
        File storageDir = Environment.getExternalStorageDirectory();
        File appDir = new File(storageDir, AppUtils.getAppNametoPath(context));
        File cachDir = new File(appDir, cachPath);
        cachDir.mkdirs();
        return cachDir;
    }

    public static File getPluginRootCacheDir(Context context) {
        File file = new File("/data/data" + File.separator + AppUtils.getPackageName() + File.separator + "pluginCache");
        file.mkdirs();
        return file;
    }

    public static File getPluginCacheDir(Context context, String pluginCachePath) {
        File file = getPluginRootCacheDir(context);
        File pluginCachDir = new File(file, pluginCachePath);
        pluginCachDir.mkdirs();
        return pluginCachDir;
    }

    public static boolean sdAvilible() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    public static boolean sdWritable() {
        File file = Environment.getExternalStorageDirectory();
        return file.canWrite();
    }

    /**
     * 返回手机号码，对于GSM网络来说即MSISDN
     * @param context
     * @return
     */
    public static String getMobile(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getLine1Number();
    }

    /**
     * 返回用户唯一标识，比如GSM网络的IMSI编号
     * @param context
     * @return
     */
    public static String getProvider(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSubscriberId();
    }

    /**
     * 返回当前移动终端的唯一标识
     * 如果是GSM网络，返回IMEI；如果是CDMA网络，返回MEID
     * @param context
     * @return
     */
    public static final String getIMEI(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * 返回用户唯一标识，比如GSM网络的IMSI编号
     * @param context
     * @return
     */
    public static String getIMSI(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSubscriberId();
    }

    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 手机型号 比如 MI 2
     * @return
     */
    public static String getModel() {
        return Build.MODEL != null?Build.MODEL.replace(" ", ""):"unknown";
    }

    /**
     * 硬件厂商
     * @return
     */
    public static String getManufacturer() {
        String manufacturer = Build.MANUFACTURER;
        return manufacturer != null?manufacturer:"unknown";
    }

    public static String getUserAgent() {
        return getManufacturer() + getModel();
    }

    public static long getSDCardFreeSpace() {
        return getFolderFreeSpace(Environment.getExternalStorageDirectory().toString());
    }

    public static long getFolderFreeSpace(String sdcard) {
        StatFs statFs = new StatFs(sdcard);
        long block;
        long available;
        if(Build.VERSION.SDK_INT >= 18) {
            block = statFs.getBlockSizeLong();
            available = statFs.getAvailableBlocksLong();
        } else {
            block = (long)statFs.getBlockSize();
            available = (long)statFs.getAvailableBlocks();
        }

        return available * block;
    }

    public static String getUniqueCode(Context context) {
        if(context == null) {
            return null;
        } else {
            try {
                return getIMEI(context) + "_" + getMacAddress(context);
            } catch (Exception var2) {
                var2.printStackTrace();
                return null;
            }
        }
    }

    public static String getMacAddress(Context context) {
        String address = "";
        String path = "/sys/class/net/wlan0/address";
        BufferedReader bufferedReader = null;

        try {
            String str;
            try {
                for(bufferedReader = new BufferedReader(new FileReader(path)); (str = bufferedReader.readLine()) != null; address = str.trim()) {

                }
            } catch (Exception var13) {
                var13.printStackTrace();
            }
        } finally {
            try {
                if(bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException io) {
                io.printStackTrace();
            }

        }

        if(TextUtils.isEmpty(address)) {
            WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wi = wm.getConnectionInfo();
            if(wi != null && !TextUtils.isEmpty(wi.getMacAddress())) {
                return wi.getMacAddress();
            }
        }

        return address;
    }

    public static String getBlueAddress() {
        String address = null;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            address = bluetoothAdapter.getAddress();
        }

        return TextUtils.isEmpty(address)?"":address;
    }

}
